#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QInputDialog>
#include "dialog.h"
#include "itemwriter.h"
#include "itemreader.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    fileName.clear();
    currentItem = 0;

    //connect(ui->actionNew_2, SIGNAL(triggered), this, SLOT(New()));
    connect(ui->treeWidget, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(dblClick(QTreeWidgetItem*, int)));

    ui->treeWidget->header()->setMovable(false);
    ui->treeWidget->header()->resizeSection(0, 250);
    ui->treeWidget->header()->resizeSection(1, 75);
    ui->treeWidget->header()->resizeSection(2, 75);
    ui->treeWidget->header()->resizeSection(6, 50);
    ui->treeWidget->header()->resizeSection(7, 50);
    ui->treeWidget->header()->resizeSection(8, 75);
    ui->treeWidget->header()->resizeSection(9, 75);
    ui->treeWidget->header()->resizeSection(10, 75);
    ui->treeWidget->header()->resizeSection(11, 75);
    ui->treeWidget->header()->resizeSection(12, 75);
    ui->treeWidget->header()->resizeSection(13, 75);
    ui->treeWidget->header()->resizeSection(14, 300);
    ui->treeWidget->header()->resizeSection(15, 75);

    resetItems();

    // STRESS TESTING //
    /*QTreeWidgetItem* p = ui->treeWidget->findItems("Weapon", Qt::MatchFixedString, 0)[0];
    while(p->parent()) p = p->parent();
    for (int i = 0; i < 50000; i++) {
        QTreeWidgetItem* item = new QTreeWidgetItem();
        item->setText(0, QString("%1").arg(i));
        p->addChild(item);
        //delete item;
    }*/

    ui->statusBar->showMessage(tr("Program started"));

   // ui->treeWidget->set
}

void MainWindow::editItem(QTreeWidgetItem* item)
{
    if (item->parent())
    {
        Dialog d(this);

        d.setWindowModality(Qt::ApplicationModal);
        d.show();
        d.raise();
        d.activateWindow();

        d.setItemName(item->text(0));
        d.setArmor(item->text(1));
        d.setDamage(item->text(2));
        d.setAttackSpeed(item->text(3));
        d.setItemLevel(item->text(4));
        d.setRequiredLevel(item->text(5));
        d.setRarity(item->text(6));
        d.setAvailableClasses(item->text(7));
        d.setStrBonus(item->text(8));
        d.setDexBonus(item->text(9));
        d.setStaBonus(item->text(10));
        d.setIntBonus(item->text(11));
        d.setWilBonus(item->text(12));
        d.setMaxCount(item->text(13));
        d.setDescription(item->text(14));
        d.setPrice(item->text(15));

        if (d.exec() == QDialog::Accepted)
        {
            item->setText(0, d.itemName());
            item->setText(1, d.armor());
            item->setText(2, d.damage());
            item->setText(3, d.attackSpeed());
            item->setText(4, d.itemLevel());
            item->setText(5, d.requiredLevel());
            item->setText(6, d.rarity());
            item->setText(7, d.availableClasses());
            item->setText(8, d.strBonus());
            item->setText(9, d.dexBonus());
            item->setText(10, d.staBonus());
            item->setText(11, d.intBonus());
            item->setText(12, d.wilBonus());
            item->setText(13, d.maxCount());
            item->setText(14, d.description());
            item->setText(15, d.price());
        }
    }
}

void MainWindow::resetItems()
{
    ui->treeWidget->clear();

    QString items[] = {"Head", "Body", "Legs", "Feet", "Hands", "Shield", "Weapon"};

    for (int i = 0; i < 7; i++)
    {
        QTreeWidgetItem* item = new QTreeWidgetItem();
        item->setText(0, items[i]);
        ui->treeWidget->addTopLevelItem(item);
    }
}

void MainWindow::dblClick(QTreeWidgetItem* item, int column)
{
    editItem(item);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionExit_triggered()
{
    exit(0);
}

void MainWindow::on_actionNew_2_triggered()
{
    Dialog d(this);

    //d.connect(ui->actionNew_2, SIGNAL(triggered), this, SLOT(New()));
    d.setWindowModality(Qt::ApplicationModal);
    d.show();
    d.raise();
    d.activateWindow();

    if (d.exec() == QDialog::Accepted)
    {
        QTreeWidgetItem* item = new QTreeWidgetItem();
        item->setText(0, d.itemName());
        item->setText(1, d.armor());
        item->setText(2, d.damage());
        item->setText(3, d.attackSpeed());
        item->setText(4, d.itemLevel());
        item->setText(5, d.requiredLevel());
        item->setText(6, d.rarity());
        item->setText(7, d.availableClasses());
        item->setText(8, d.strBonus());
        item->setText(9, d.dexBonus());
        item->setText(10, d.staBonus());
        item->setText(11, d.intBonus());
        item->setText(12, d.wilBonus());
        item->setText(13, d.maxCount());
        item->setText(14, d.description());
        item->setText(15, d.price());

        QTreeWidgetItem* parent = ui->treeWidget->currentItem();
        while(parent->parent()) parent = parent->parent();

        parent->addChild(item);
    }
}

void MainWindow::on_actionNew_triggered()
{
    resetItems();
    fileName.clear();
}

void MainWindow::on_actionEdit_triggered()
{

    editItem(ui->treeWidget->currentItem());
}

void MainWindow::on_actionRemove_triggered()
{
    QTreeWidgetItem* item = ui->treeWidget->currentItem();
    if (item->parent())
    {
        delete item;
    }
}

void MainWindow::on_actionAbout_triggered()
{
    QMessageBox msgBox;
    msgBox.about(this, tr("About Item Editor"), tr("Item Editor v0.1\n\nCopyright 2012 Lauri Haavisto.\nAll rights reserved."));
}

void MainWindow::on_actionLoad_triggered()
{
    fileName = QFileDialog::getOpenFileName(this, tr("Open file"), "", tr("Unnamed RPG Item File (*.uif)"));

    if (!fileName.isEmpty())
    {
        resetItems();
        QFile file(fileName);
        file.open(QIODevice::ReadOnly);
        itemReader reader(ui->treeWidget);
        if (reader.readFile(&file))
            ui->statusBar->showMessage(tr("Loaded %1 items from %2").arg(reader.getItemCount()).arg(fileName));
        else
        {
            resetItems();
            ui->statusBar->showMessage(tr("Error loading items from %1: '%2'").arg(fileName).arg(reader.errorString()));
        }
        file.close();
    }
}

void MainWindow::on_actionSave_triggered()
{
    if (fileName.isEmpty())
        fileName = QFileDialog::getSaveFileName(this, tr("Save file"), "", tr("Unnamed RPG Item File (*.uif)"));

    if (!fileName.isEmpty())
    {
        QFile file(fileName);
        file.open(QIODevice::WriteOnly);
        itemWriter writer(ui->treeWidget);
        if (writer.writeFile(&file))
            ui->statusBar->showMessage(tr("%1 items saved to %2").arg(writer.getItemCount()).arg(fileName));
        file.close();
    }
}

void MainWindow::on_actionSave_as_triggered()
{
    fileName = QFileDialog::getSaveFileName(this, tr("Save file"), "", tr("Unnamed RPG Item File (*.uif)"));

    if (!fileName.isEmpty())
    {
        QFile file(fileName);
        file.open(QIODevice::WriteOnly);
        itemWriter writer(ui->treeWidget);
        if (writer.writeFile(&file))
            ui->statusBar->showMessage(tr("%1 items saved to %2").arg(writer.getItemCount()).arg(fileName));
        file.close();
    }
}

void MainWindow::on_actionFind_triggered()
{
    QString itemName = QInputDialog::getText(this, tr("Find item"), tr("Item:"), QLineEdit::Normal, "");

    if (!itemName.isEmpty())
    {
        foundItems = ui->treeWidget->findItems(itemName, Qt::MatchContains | Qt::MatchRecursive, 0);
        if (!foundItems.isEmpty())
        {
            ui->statusBar->showMessage(tr("Found %1 items matching %2").arg(foundItems.count()).arg(itemName));
            currentItem = 0;

            ui->treeWidget->scrollToItem(foundItems[currentItem]);
            ui->treeWidget->setCurrentItem(foundItems[currentItem]);
        }
        else
        {
            ui->statusBar->showMessage(tr("Couldn't find any item matching %1").arg(itemName));
        }
    }
}

void MainWindow::on_actionFind_Next_triggered()
{
    if (!foundItems.isEmpty())
    {
        if (currentItem < foundItems.count() - 1)
        {
            currentItem++;

            ui->treeWidget->scrollToItem(foundItems[currentItem]);
            ui->treeWidget->setCurrentItem(foundItems[currentItem]);
        }
        else
        {
            ui->statusBar->showMessage(tr("Cannot find item"));
        }
    }
}

void MainWindow::on_actionJoin_File_triggered()
{
    fileName = QFileDialog::getOpenFileName(this, tr("Join file"), "", tr("Unnamed RPG Item File (*.uif)"));

    if (!fileName.isEmpty())
    {
        QFile file(fileName);
        file.open(QIODevice::ReadOnly);
        itemReader reader(ui->treeWidget);
        if (reader.readFile(&file))
            ui->statusBar->showMessage(tr("Joined %1 items from %2").arg(reader.getItemCount()).arg(fileName));
        else
        {
            resetItems();
            ui->statusBar->showMessage(tr("Error joining items from %1: '%2'").arg(fileName).arg(reader.errorString()));
        }
        file.close();
    }
}
